﻿#region " LICENSE "
// DRILL - Dependency Resolution Interface Layer Library
// Copyright (c) 2008-2012 Wade A. Reynolds. All rights reserved.
// http://drill.codeplex.com/
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Drill.Configuration;
using Drill.Core;
using Drill.Core.MasterFactories;

namespace Drill
{
	public static class DependencyResolverManager
	{
		private static readonly ConcurrentDictionary<string, IDependencyResolver> _resolvers;
		private static readonly DependencyResolverManagementDictionary _readOnlyResolvers;

		/// <summary>
		/// Initializes the <see cref="DependencyResolverManager" /> class.
		/// </summary>
		static DependencyResolverManager()
		{
			_resolvers = new ConcurrentDictionary<string, IDependencyResolver>();
			_readOnlyResolvers = new DependencyResolverManagementDictionary(_resolvers);
		}

		/// <summary>
		/// Creates a new dependency resolver from the specified confgiuration.
		/// </summary>
		/// <param name="config">The configuration used to build the <see cref="IDependencyResolver" /> instance.</param>
		/// <returns>
		/// A new <see cref="IDependencyResolver" /> instance.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">config</exception>
		/// <remarks>
		/// This method creates the <see cref="IDependencyResolver" /> instance.
		/// It does not register the instance.
		/// </remarks>
		public static IDependencyResolver Create(IDependencyResolverConfiguration config)
		{
			if (null == config)
			{
				throw new ArgumentNullException("config");
			}

			IDependencyResolverFactory factory = new ConfigBasedMasterDependencyResolverFactory(config);
			IDependencyResolver dependencyResolver = factory.CreateDependencyResolver();
			return dependencyResolver;
		}

		/// <summary>
		/// Creates a new dependency resolver from the specified confgiuration 
		/// and registers it with the DependencyResolverManager.
		/// </summary>
		/// <param name="config">
		/// The configuration used to build the <see cref="IDependencyResolver" /> instance.
		/// </param>
		/// <param name="name">The unique name used to register the dependency resolver.</param>
		/// <returns>
		/// A new <see cref="IDependencyResolver" /> instance that has been 
		/// registered with the DependencyResolverManager.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">config</exception>
		/// <exception cref="Drill.DependencyResolverException">
		/// A dependency resolver with the specified name is already registered.
		/// </exception>
		/// <remarks>
		/// If a name is not specified, the configured name of the dependency resolver is used 
		/// as the registration key.
		/// </remarks>
		public static IDependencyResolver CreateAndRegister(IDependencyResolverConfiguration config, string name = null)
		{
			if (null == config)
			{
				throw new ArgumentNullException("config");
			}

			// Determine the key and verify it before doing any real work.
			string key = string.IsNullOrEmpty(name) ? config.Name : name;

			if (string.IsNullOrWhiteSpace(key))
			{
				throw new ArgumentException(
					"The value of the config parameter's Name property is null, empty or whitespace. "
				  + "This name is used to register the dependency resolver instance with the "
				  + "DependencyResolverManager, but the name is not valid."
				  , "config"
					);
			}

			// Althought his check is repeated in the Register method, it is better 
			// to also perform the check here before any work is performed.
			if (IsRegistered(key))
			{
				throw new DependencyResolverException("A dependency resolver with the name '{0}' is already registered.", key);
			}

			IDependencyResolver dependencyResolver = Create(config);
			Register(key, dependencyResolver);
			return dependencyResolver;
		}

		/// <summary>
		/// Determines whether the specified name is registered.
		/// </summary>
		/// <param name="name">The name to check.</param>
		/// <returns>
		///   <c>true</c> if the specified name is registered; otherwise, <c>false</c>.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">name</exception>
		public static bool IsRegistered(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentNullException("name");
			}
			return _resolvers.ContainsKey(name);
		}

		/// <summary>
		/// Registers the specified dependency resolver with the specified name with the DependencyResolverManager.
		/// </summary>
		/// <param name="name">The unique name used to register the dependency resolver.</param>
		/// <param name="dependencyResolver">The dependency resolver to be registered.</param>
		/// <exception cref="System.ArgumentNullException">name</exception>
		/// <exception cref="Drill.DependencyResolverException">
		/// A dependency resolver with the specified name is already registered.
		/// </exception>
		public static void Register(string name, IDependencyResolver dependencyResolver)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentNullException("name");
			}

			if (null == dependencyResolver)
			{
				throw new ArgumentNullException("dependencyResolver");
			}

			if (IsRegistered(name))
			{
				throw new DependencyResolverException("A dependency resolver with the name '{0}' is already registered.", name);
			}

			// Add the dependency resolver to the _resolvers dictionary.
			if (false == _resolvers.TryAdd(name, dependencyResolver))
			{
				throw new DependencyResolverException("The dependency resolver could not be registerd. This may be caused by a concurrency issue.");
			}
		}

		/// <summary>
		/// Unregisters the dependency resolver that was registered with the specified name.
		/// </summary>
		/// <param name="name">The registered name of the dependency resolver to unregister.</param>
		/// <exception cref="System.ArgumentNullException">name</exception>
		public static void Unregister(string name)
		{
			IDependencyResolver dependencyResolver;

			if (string.IsNullOrWhiteSpace(name) 
				|| false == IsRegistered(name)
				|| false == _resolvers.TryRemove(name, out dependencyResolver)
				)
			{
				return;
			}

			if (null != dependencyResolver)
			{
				dependencyResolver.Dispose();
			}
		}

		/// <summary>
		/// Resets the DependencyResolverManager and removes and disposes all dependency resolvers.
		/// </summary>
		public static void Reset()
		{
			_resolvers.Keys.ToList().ForEach(Unregister);
			_resolvers.Clear();
		}

		/// <summary>
		/// Gets the read-only dependency resolvers dictionary.
		/// </summary>
		/// <value>The read-only dependency resolvers dictionary.</value>
		public static IDictionary<string, IDependencyResolver> Resolvers { get { return _readOnlyResolvers; } }
	}
}